package cn.kgc.listener;

import cn.kgc.base.dto.LockStockDTO;
import cn.kgc.base.vo.OrderVo;
import cn.kgc.client.OmsOrderFeignClient;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.commons.vo.Result;
import cn.kgc.constant.OrderStatusEnum;
import cn.kgc.entity.WmsWareInfo;
import cn.kgc.entity.WmsWareSku;
import cn.kgc.service.WmsWareInfoService;
import cn.kgc.service.WmsWareSkuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class WmsWareSkuListener {
    @Resource
    private OmsOrderFeignClient omsOrderFeignClient;
    @Resource
    private WmsWareSkuService wmsWareSkuService;
    @RabbitListener(queues = "stock.unlock.queue")
    public void receiveUnLockStockMessage(List<LockStockDTO> lockStockDTOList, Channel channel, Message message) {
        long tag= message.getMessageProperties().getDeliveryTag();
        try {
            //释放库存，获得释放订单库存的编号
            String orderSn = lockStockDTOList.get(0).getOrderSn();
            // 根据订单的编号获得订单的状态，如果是已经关闭，释放库存
            Result<OrderVo> result=omsOrderFeignClient.getOrderInfoByOrderSn(orderSn);
            //1 服务降级 没有拿到订单数据 重新获得订单的数据 抛出异常信息
            if(result.getMessage().equals("error")){
                throw new HttpException(50003,HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
            //2 服务没有降级 拿到订单数据 但是我们根据订单的编号获得的订单为null时，需要解锁库存
            if (result.getData()==null){
                wmsWareSkuService.unlockStock(lockStockDTOList);
            } else {
                // 3 服务没有降级 拿到订单数据 但是我们根据订单的编号获得的订单不为null时，订单状态已经关闭 解锁库存
                OrderVo orderVo=result.getData();
                if (orderVo.getStatus()== OrderStatusEnum.CLOSED.getOrderStatus()){
                    wmsWareSkuService.unlockStock(lockStockDTOList);
                }
            }
            //手动确认消息
            channel.basicAck(tag,false);
        } catch (IOException e) {
            try {
                log.error("释放库存失败，订单编号：{}",lockStockDTOList.get(0).getOrderSn());
                //Thread.sleep(1000);
                channel.basicNack(tag,false,true);
            } catch (IOException ex) {
                log.error("释放库存失败，订单编号：{}",lockStockDTOList.get(0).getOrderSn());
            }
        }
    }
}
